﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web.Http;

using ERPStore.Extensions;
using ERPStore.Host.Extensions;

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

using CloudSoft.Extensions;

using Microsoft.Owin;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Hosting;

using Owin;



namespace ERPStore.Host
{
	public class Hoster
	{
		ERPStore.Logging.ILogger m_Logger = null;
		IDisposable m_SelfHostServer;

		public void Initialize()
		{

		}

		public void Start()
		{
			StartServices();
		}

		public void Stop()
		{
			GlobalConfiguration.Configuration.Logger.Notification("SvcHost for {0}@{1} stopping", ERPStore.GlobalConfiguration.Configuration.Settings.ApplicationName, System.Environment.MachineName);

			var container = ERPStore.GlobalConfiguration.Configuration.DependencyResolver.GetContainer();
			var eventPublisher = container.Resolve<EventBrokR.IPublisher>();
			eventPublisher.PublishAsync(new ERPStore.Events.EndApplicationRequestedEvent());

			Logging.AsyncLogger.Current.Stop();

			if (m_SelfHostServer != null)
			{
				m_SelfHostServer.Dispose();
			}

			Logging.AsyncLogger.Current.Terminate();
		}

		public void Pause()
		{
			// m_ServiceBus.PauseReading();
		}

		internal void StartServices()
		{
			var location = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location);
			var container = Host.Start.UnityConfig.GetConfiguredContainer(location);

			var startingMessage = string.Format("{0} for {1}@{2} starting, executing context : {3} debug : {4}", 
				ERPStore.GlobalConfiguration.Configuration.HosterName, 
				location, 
				System.Environment.MachineName,
				ERPStore.GlobalConfiguration.Configuration.ExecutingContext,
				ERPStore.GlobalConfiguration.Configuration.DebugEnabled);

			Console.WriteLine(startingMessage);
			ERPStore.GlobalConfiguration.Configuration.Logger.Info(startingMessage);

			Host.Start.HostConfig.ConfigureSettings(container, location);
			Host.Start.PluginsConfig.LoadPlugins(container, location);
			m_SelfHostServer = Host.Start.OwinConfig.StartSelfHosting();

			var eventPublisher = container.Resolve<EventBrokR.IPublisher>();
			eventPublisher.PublishAsync(new ERPStore.Events.ApplicationStartedEvent());

			ERPStore.GlobalConfiguration.Configuration.Logger.Notification("SvcHost for {0}@{1} started", ERPStore.GlobalConfiguration.Configuration.Settings.ApplicationName, System.Environment.MachineName);
			Console.WriteLine("SvcHost for {0}@{1} started", ERPStore.GlobalConfiguration.Configuration.Settings.ApplicationName, System.Environment.MachineName);
		}

	}
}
